﻿using DevExpress.ExpressApp.ConditionalAppearance;
using DevExpress.ExpressApp.Editors;
using DevExpress.ExpressApp.Security;
using DevExpress.Persistent.Base;
using DevExpress.Persistent.BaseImpl.PermissionPolicy;
using DevExpress.Xpo;
using System.ComponentModel;

namespace EasyXaf.RendererTest.Sample.Module.BusinessObjects;

[MapInheritance(MapInheritanceType.ParentTable)]
[DefaultProperty(nameof(UserName))]
public class ApplicationUser : PermissionPolicyUser, ISecurityUserWithLoginInfo, ISecurityUserLockout
{
    private int accessFailedCount;
    private DateTime lockoutEnd;

    [EditorAlias("CustomTextEditor")]
    [Appearance("当IsActive为False时，不显示", Criteria = "[IsActive] = false", Visibility = ViewItemVisibility.Hide)]
    public string DescriptionA
    {
        get => GetPropertyValue<string>(nameof(DescriptionA));
        set => SetPropertyValue(nameof(DescriptionA), value);
    }

    [EditorAlias("CustomTextEditor")]
    public string DescriptionB
    {
        get => GetPropertyValue<string>(nameof(DescriptionB));
        set => SetPropertyValue(nameof(DescriptionB), value);
    }

    [EditorAlias("CustomTextEditor")]
    public string DescriptionC
    {
        get => GetPropertyValue<string>(nameof(DescriptionC));
        set => SetPropertyValue(nameof(DescriptionC), value);
    }

    [EditorAlias("CustomTextEditor")]
    public string DescriptionD
    {
        get => GetPropertyValue<string>(nameof(DescriptionD));
        set => SetPropertyValue(nameof(DescriptionD), value);
    }

    public ApplicationUser(Session session) : base(session)
    {
        DescriptionA = "A组件";
        DescriptionB = "B组件";
        DescriptionC = "C组件";
        DescriptionD = "D组件";
    }

    [Browsable(false)]
    public int AccessFailedCount
    {
        get { return accessFailedCount; }
        set { SetPropertyValue(nameof(AccessFailedCount), ref accessFailedCount, value); }
    }

    [Browsable(false)]
    public DateTime LockoutEnd
    {
        get { return lockoutEnd; }
        set { SetPropertyValue(nameof(LockoutEnd), ref lockoutEnd, value); }
    }

    [Browsable(false)]
    [Aggregated, Association("User-LoginInfo")]
    public XPCollection<ApplicationUserLoginInfo> LoginInfo
    {
        get { return GetCollection<ApplicationUserLoginInfo>(nameof(LoginInfo)); }
    }

    IEnumerable<ISecurityUserLoginInfo> IOAuthSecurityUser.UserLogins => LoginInfo.OfType<ISecurityUserLoginInfo>();

    ISecurityUserLoginInfo ISecurityUserWithLoginInfo.CreateUserLoginInfo(string loginProviderName, string providerUserKey)
    {
        ApplicationUserLoginInfo result = new ApplicationUserLoginInfo(Session);
        result.LoginProviderName = loginProviderName;
        result.ProviderUserKey = providerUserKey;
        result.User = this;
        return result;
    }
}
